package com.example.cemenghuii.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.cemenghuii.config.WeChatConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatService {

    @Autowired
    private WeChatConfig weChatConfig;

    /**
     * 通过code获取微信用户的openId和sessionKey
     */
    public Map<String, Object> code2Session(String code) {
        String url = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                weChatConfig.getLoginUrl(),
                weChatConfig.getAppId(),
                weChatConfig.getAppSecret(),
                code);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);

            String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            JSONObject jsonObject = JSON.parseObject(responseBody);

            Map<String, Object> result = new HashMap<>();

            if (jsonObject.containsKey("errcode")) {
                // 有错误
                result.put("success", false);
                result.put("errcode", jsonObject.getInteger("errcode"));
                result.put("errmsg", jsonObject.getString("errmsg"));
            } else {
                // 成功
                result.put("success", true);
                result.put("openid", jsonObject.getString("openid"));
                result.put("session_key", jsonObject.getString("session_key"));
                result.put("unionid", jsonObject.getString("unionid"));
            }

            return result;

        } catch (IOException e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("errcode", -1);
            errorResult.put("errmsg", "网络请求失败：" + e.getMessage());
            return errorResult;
        }
    }

    /**
     * 获取微信AccessToken
     */
    public String getAccessToken() {
        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                weChatConfig.getAppId(),
                weChatConfig.getAppSecret());

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);

            String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            JSONObject jsonObject = JSON.parseObject(responseBody);

            if (jsonObject.containsKey("access_token")) {
                return jsonObject.getString("access_token");
            } else {
                throw new RuntimeException("获取AccessToken失败：" + jsonObject.getString("errmsg"));
            }

        } catch (IOException e) {
            throw new RuntimeException("获取AccessToken网络请求失败：" + e.getMessage());
        }
    }

    /**
     * 验证微信用户信息
     */
    public boolean validateUserInfo(String sessionKey, String rawData, String signature) {
        // 这里可以实现微信用户信息的验证逻辑
        // 使用session_key对rawData进行sha1加密，与signature比较
        return true; // 简化实现，实际项目中需要严格验证
    }

    /**
     * 解密微信用户敏感数据
     */
    public JSONObject decryptData(String sessionKey, String encryptedData, String iv) {
        // 这里可以实现AES解密逻辑
        // 解密微信用户的敏感数据，如手机号等
        return new JSONObject(); // 简化实现
    }

    /**
     * 发送模板消息
     */
    public boolean sendTemplateMessage(String openId, String templateId, Map<String, Object> data) {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;

        Map<String, Object> message = new HashMap<>();
        message.put("touser", openId);
        message.put("template_id", templateId);
        message.put("data", data);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 这里需要实现POST请求发送模板消息
            // 简化实现，实际项目中需要完整实现
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 生成小程序码
     */
    public byte[] generateWxaCode(String scene, String page) {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;

        Map<String, Object> params = new HashMap<>();
        params.put("scene", scene);
        if (page != null) {
            params.put("page", page);
        }
        params.put("width", 430);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 这里需要实现POST请求生成小程序码
            // 简化实现，返回空数组
            return new byte[0];
        } catch (Exception e) {
            return new byte[0];
        }
    }

    /**
     * 检查内容安全
     */
    public boolean checkContentSecurity(String content) {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + accessToken;

        Map<String, Object> params = new HashMap<>();
        params.put("content", content);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 这里需要实现POST请求检查内容安全
            // 简化实现，默认返回安全
            return true;
        } catch (Exception e) {
            return true;
        }
    }

    /**
     * 获取用户基本信息（需要用户授权）
     */
    public JSONObject getUserInfo(String accessToken, String openId) {
        String url = String.format("https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN",
                accessToken, openId);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);

            String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            return JSON.parseObject(responseBody);

        } catch (IOException e) {
            return new JSONObject();
        }
    }
}